import get from 'lodash-es/get.js';
import { bdToGd } from './translator.js';
export class BasicMarker {
  /*
   * data: {title: "",lnglat: [],icon: ""}
   * */
  constructor({ map, data }) {
    this.map = map;
    this.data = Object.assign({}, data, {
      lnglat: this.getPosition(data),
    });
    this.anchor = 'bottom-center';
    this.offset = { x: 1, y: 1 };
    /* 各种事件的前置处理 */
    this.preIntercept = {};
  }
  create() {
    const { data } = this;
    this.marker = new AMap.Marker(
      Object.assign(this.getIconOption(this.getIcon(data)), {
        anchor: this.anchor,
        title: this.getTitle(),
        position: data.lnglat,
        extData: data,
        label: { content: this.getTitle(), direction: 'top', offset: new AMap.Pixel(0, 0) },
      })
    );
    let label = this.getLabel();
    if (label && label.content) {
      this.marker.setLabel(label);
    }
    this.on('click', this.onClick, this);
    this.on('rightclick', this.onRightClick, this);
    return this;
  }
  on(event, handle, ctx) {
    if (!this.marker) return;
    this.marker.on(event, (e) => {
      let next = true;
      if (typeof this.preIntercept[event] === 'function') {
        next = this.preIntercept[event](e) !== false;
      }
      if (next && typeof handle === 'function') {
        ctx !== undefined ? handle.call(ctx, e) : handle(e);
      }
    });
  }
  getMarker() {
    return this.marker;
  }
  getTitle() {
    return this.data.name;
  }
  getLabel() {
    return {
      content: this.getLabelContent(),
      direction: 'top',
      offset: new AMap.Pixel(0, 0),
    };
  }
  getLabelContent() {
    const label = this.data.label || '';
    return label ? `<div style="color: #fff">${label || ''}</div>` : '';
  }
  getPosition(data) {
    let lng = get(data, 'lnglat[0]');
    let lat = get(data, 'lnglat[1]');
    return bdToGd(lng, lat);
  }
  getIcon(data) {
    return data.icon;
  }
  getIconOption(icon) {
    return {
      content: `<img src="${icon}" style="width: 38px;height: 56px;" />`,
      offset: new AMap.Pixel(-19, -56),
    };
  }
  getVisible() {
    const map = this.marker.getMap();
    return map instanceof AMap.Map;
  }
  show() {
    this.marker.setMap(this.map);
    return this;
  }
  hide() {
    this.marker.setMap(null);
    return this;
  }
  onClick(e) {
    // console.log(e);
  }
  onRightClick(e) {}
}
